/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.archivers.zip;

import com.softwarecraftsmen.archivers.Archiver;
import com.softwarecraftsmen.archivers.zip.zipEntryAndData.AbsoluteFileBackedZipEntryAndData;
import com.softwarecraftsmen.archivers.zip.zipEntryAndData.ZipEntryAndData;
import com.softwarecraftsmen.orogeny.filing.AbsoluteDirectories;
import com.softwarecraftsmen.orogeny.filing.AbsoluteDirectory;
import com.softwarecraftsmen.orogeny.filing.AbsoluteFile;
import com.softwarecraftsmen.orogeny.filing.RelativeFile;
import com.softwarecraftsmen.orogeny.filing.findFileFilters.FindFilesFilter;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class ZipArchiver implements Archiver
{
	@NotNull
	public static final ZipArchiver ZipArchive = new ZipArchiver();

	private ZipArchiver()
	{}

	public void archive(final @NotNull AbsoluteFile archiveFile, final @NotNull AbsoluteDirectories archiveRoots, final @NotNull FindFilesFilter includeFiles) throws IOException
	{
		final LinkedHashSet<ZipEntryAndData> zipEntriesAndTheirData = new LinkedHashSet<ZipEntryAndData>()
		{{
			for (AbsoluteDirectory archiveRoot : archiveRoots)
			{
				for (AbsoluteFile fileToArchive : archiveRoot.findFiles(includeFiles))
				{
					final RelativeFile fileInArchive = fileToArchive.toRelativeFile(archiveRoot);
					add(new AbsoluteFileBackedZipEntryAndData(fileToArchive, fileInArchive));
				}
			}}
		};
		archive(archiveFile, zipEntriesAndTheirData);
	}

	public void archive(final @NotNull AbsoluteFile archiveFile, final @NotNull Set<ZipEntryAndData> zipEntriesAndTheirData) throws IOException
	{
		archive(archiveFile, zipEntriesAndTheirData.iterator());
	}

	public void archive(final @NotNull AbsoluteFile archiveFile, final @NotNull Iterator<ZipEntryAndData> zipEntriesAndTheirData) throws IOException
	{
		archiveFile.writeData(new ZipOutputStreamWriter(zipEntriesAndTheirData));
	}

	@NotNull
	public String toString()
	{
		return "ZipArchive";
	}
}
